package server.map;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;


import server.main.Data;
import server.mobiles.Mobile;
import server.utility.Id;
import server.utility.Point2d;


public class Map implements Serializable {

	private static final long serialVersionUID = 1L;
	private Point2d top, bottom;
	private String name;
	private Id id;
	private ArrayList<Mobile> mobiles;
	private ArrayList<Gate> gates;
	private ArrayList<Platform> platforms;
	private ArrayList<Stair> stairs;
	
	public Map(Point2d top, Point2d bottom, String name, Id id) {
		super();
		this.top = top;
		this.bottom = bottom;
		this.name = name;
		this.id = id;
		mobiles=new ArrayList<Mobile>();
		gates=new ArrayList<Gate>();
		platforms=new ArrayList<Platform>();
		stairs=new ArrayList<Stair>();
	}
	
	public void addGate(Gate g){
		gates.add(g);
	}
	
	public void addPlatform(Platform p){
		platforms.add(p);
	}
	
	public void onEnter(Mobile m){
		mobiles.add(m);
	}
	
	public void onExit(Mobile m){
		mobiles.remove(m);
	}
	
	public void onKilled(Mobile m){
		mobiles.remove(m);
		Data.remove(m);
	}
	
	public void spawn(Point2d p, Mobile m){
		m.setPosition(p);
		m.setMap(this.id);
		//mobiles.add(m);
		
		Data.add(m);
	}

	public Id getId() {
		return id;
	}

	public ArrayList<Mobile> getMobiles() {
		return mobiles;
	}
	
	private void readObject(ObjectInputStream in) throws IOException,
	ClassNotFoundException {
		int ver=in.readInt();
		
		switch(ver){
		
			case 1:{
				top = (Point2d)in.readObject();
				bottom = (Point2d)in.readObject();
				name = in.readUTF();
				id = (Id)in.readObject();
				mobiles = (ArrayList<Mobile>)in.readObject();
				gates=(ArrayList<Gate>) in.readObject();
				platforms=(ArrayList<Platform>) in.readObject();
				stairs=(ArrayList<Stair>) in.readObject();
			}
		}
	}
	
	private void writeObject(ObjectOutputStream out) throws IOException {
		out.writeInt(1); //version
		
		out.writeObject(top);
		out.writeObject(bottom);
		out.writeUTF(name);
		out.writeObject(id);
		out.writeObject(mobiles);
		out.writeObject(gates);
		out.writeObject(platforms);
		out.writeObject(stairs);
	}

	public Gate getGate(Point2d position) {
		for(Gate g:gates){
			if(g.isInside(position))
				return g;
		}
		
		return null;
	}

	public void addStair(Stair s) {
		stairs.add(s);
	}

	public Stair getStair(Point2d position) {
		for(Stair s:stairs){
			if(s.isInside(position))
				return s;
		}
		
		return null;
	}

	public Platform getPlatform(Point2d position) {
		for(Platform p:platforms){
			if(p.isPosed(position))
				return p;
		}
		
		return null;
	}
}